from django.db.models import Count, F

# sorting collections by one field
def sorting_by_single_field(collections, ordering_params, mapping_field):
    if ordering_params is not None:
        ordering_set = ordering_params.split(',')
        order_field = ordering_set[0]
        order_pattern = ordering_set[1]
        if mapping_field.get(order_field) is not None:
            order_field = mapping_field[order_field]
        order_combine = ('-' if (order_pattern == 'DESC') else '') + order_field
        return collections.order_by(order_combine)
    else:
        return collections


# sorting collections by on field maybe count ordering
# func_count_field will count the given relation set or id size by Count function
def sorting_by_single_field_with_funcs(collections, ordering_params, mapping_field, func_count_field, func_f_field):
    if ordering_params is not None:
        ordering_set = ordering_params.split(',')
        order_field = ordering_set[0]
        order_pattern = ordering_set[1]
        if func_count_field.get(order_field) is not None:
            return collections.annotate(count=Count(func_count_field.get(order_field))).order_by(
                ('-' if (order_pattern == 'DESC') else '') + 'count')
        if func_f_field.get(order_field) is not None:
            return collections.annotate(f_func_val=F(func_f_field.get(order_field))).order_by(
                ('-' if (order_pattern == 'DESC') else '') + 'f_func_val')
        if mapping_field.get(order_field) is not None:
            order_field = mapping_field[order_field]
        return collections.order_by(('-' if (order_pattern == 'DESC') else '') + order_field)
    else:
        return collections
